package com.mgy.example.exception;

import com.mgy.example.domain.common.WebResponse;
import com.mysql.jdbc.exceptions.MySQLTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常拦截处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 参数错误
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public WebResponse IllegalArgumentException(IllegalArgumentException e) {
        logger.error(e.getMessage(), e);
        WebResponse webResponse = new WebResponse();
        webResponse.setResult(201);
        webResponse.setMessage("参数错误发生错误！" + e.getMessage());
        return webResponse;
    }

    /**
     * 通用异常
     */
    @ExceptionHandler(Exception.class)
    public WebResponse CommonException(Exception e) {
        WebResponse webResponse = new WebResponse();
        logger.error(e.getMessage(), e);
        if (e instanceof UncategorizedSQLException) {
            if (e.getCause() != null && e.getCause().getCause() instanceof MySQLTimeoutException) {
                webResponse.setResult(301);
                webResponse.setMessage("数据库连接超时！");
                return webResponse;
            }
        }
        webResponse.setResult(300);
        webResponse.setMessage(e.getMessage());
        return webResponse;
    }

    /**
     * 空指针
     */
    @ExceptionHandler(NullPointerException.class)
    public WebResponse NullPointerException(NullPointerException e) {
        WebResponse webResponse = new WebResponse();
        webResponse.setResult(301);
        logger.error(e.getMessage(), e);
        webResponse.setMessage("程序发生空指针错误！" + e.getMessage());
        return webResponse;
    }

    /**
     * dao层数据更新异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(DataAccessException.class)
    public WebResponse DataAccessException(DataAccessException e) {
        logger.error(e.getMessage(), e);
        WebResponse webResponse = new WebResponse();
        webResponse.setResult(302);
        webResponse.setMessage("数据更新发生错误！" + e.getMessage());
        return webResponse;
    }

    /**
     * 拦截请求资源不存在
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public WebResponse NoHandlerFoundException(NoHandlerFoundException e) {
        logger.error(e.getMessage(), e);
        WebResponse webResponse = new WebResponse();
        webResponse.setResult(404);
        webResponse.setMessage("请求资源不存在！" + e.getMessage());
        webResponse.setApiName(e.getRequestURL());
        return webResponse;
    }

}
